package com.feeyo.groundservice.checkin.dlg

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableLongState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.blankj.utilcode.util.ScreenUtils
import com.feeyo.groundservice.base_util.SuccessCallback
import com.feeyo.groundservice.base_util.dealString
import com.feeyo.groundservice.base_util.formatTimeHMWithDay
import com.feeyo.groundservice.base_util.formatTimeYMDHM
import com.feeyo.groundservice.base_util.toSeconds
import com.feeyo.groundservice.base_util.toastCenter
import com.feeyo.groundservice.checkin.R
import com.feeyo.groundservice.checkin.base.AppDataStore
import com.feeyo.groundservice.checkin.constant.checkInListRefreshFlag
import com.feeyo.groundservice.checkin.constant.statusBarColor
import com.feeyo.groundservice.checkin.databinding.ViewCommonPopBinding
import com.feeyo.groundservice.checkin.model.CheckInAreaItemBO
import com.feeyo.groundservice.checkin.model.CheckInPerSonBO
import com.feeyo.groundservice.checkin.viewmodel.CheckInViewModel
import com.feeyo.groundservice.composewidget.util.dimenToDp
import com.feeyo.groundservice.composewidget.util.dimenToSp
import com.feeyo.groundservice.composewidget.util.drawableToPainter
import com.feeyo.groundservice.composewidget.util.intervalClick
import com.feeyo.groundservice.composewidget.util.toComposeColor
import com.feeyo.groundservice.composewidget.view.button.CustomButton
import com.feeyo.groundservice.composewidget.view.tab.SwitchTab
import com.feeyo.groundservice.composewidget.view.tab.TabRowItem
import com.feeyo.groundservice.composewidget.view.util.HorizontalSpace
import com.feeyo.groundservice.composewidget.view.util.VerticalSpace
import com.feeyo.groundservice.time_address.popup.TimePickerPopup

/**
 *作者：QLH on 2025-10-27
 *描述：新增值机
 */
internal class AddCheckInPopView(context: Context) : BaseBottomCalendarPop(context) {

    init {
        id = android.R.id.content
        setViewTreeLifecycleOwner(context as AppCompatActivity)
        setViewTreeSavedStateRegistryOwner(context as AppCompatActivity)
    }

    private lateinit var binding: ViewCommonPopBinding

    private val areaBO = mutableStateOf<CheckInAreaItemBO?>(null)
    private val userBO = mutableStateOf<CheckInPerSonBO?>(null)
    private val startTime = mutableLongStateOf(System.currentTimeMillis().toSeconds())
    private val endTime = mutableLongStateOf(System.currentTimeMillis().toSeconds() + 60 * 60)

    override fun getImplLayoutId(): Int {
        return R.layout.view_common_pop
    }

    override fun setPickMode() {
        setPickMode(TimePickerPopup.Mode.YMDHM)
    }

    override fun onCreate() {
        super.onCreate()
        binding = ViewCommonPopBinding.bind(this.popupImplView)
        binding.popCp.apply {
            setContent {
                val viewModel: CheckInViewModel = viewModel(context as AppCompatActivity)
                val selectedIsland = remember { mutableStateOf("") }
                Column(
                    modifier = Modifier.fillMaxWidth()
                        .verticalScroll(rememberScrollState())
                        .background(
                            color = R.color.white.toComposeColor(),
                            shape = RoundedCornerShape(
                                topStart = R.dimen.d12.dimenToDp(),
                                topEnd = R.dimen.d12.dimenToDp(),
                            )
                        )
                        .padding(R.dimen.d15.dimenToDp())
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "新增值机",
                            fontSize = R.dimen.d15.dimenToSp(),
                            fontWeight = FontWeight.W600,
                            color = R.color.black_33.toComposeColor(),
                        )

                        Icon(
                            painter = R.drawable.icon_edt_clear_blue.drawableToPainter(),
                            contentDescription = null,
                            tint = R.color.gray_C0.toComposeColor(),
                            modifier = Modifier.size(R.dimen.d22.dimenToDp())
                                .intervalClick { dismiss() }
                        )
                    }

                    VerticalSpace(R.dimen.d20.dimenToDp())
                    //值机岛选择
                    CheckInIslandView(
                        onSelectedIsland = {
                            selectedIsland.value = it
                        }
                    )
                    VerticalSpace(R.dimen.d20.dimenToDp())
                    //保障人员和计划时间
                    CheckInPersonView()
                    Spacer(modifier = Modifier.weight(1f))
                    CustomButton(
                        modifier = Modifier.fillMaxWidth(0.5f).height(R.dimen.d36.dimenToDp())
                            .padding(
                                vertical = R.dimen.d10.dimenToDp()
                            )
                            .align(Alignment.CenterHorizontally),
                        bgs = listOf(
                            statusBarColor.toComposeColor(),
                            statusBarColor.toComposeColor().copy(0.8f)
                        ),
                        cornerShape = RoundedCornerShape(R.dimen.d5.dimenToDp()),
                        onClick = {
                            //校验数据
                            if (validateData()) {
                                viewModel.addCheckIn(
                                    title = "",
                                    startTime = startTime.longValue,
                                    endTime = endTime.longValue,
                                    uid = userBO.value?.uid ?: "",
                                    checkInStation = areaBO.value?.title ?: "",
                                    listener = object : SuccessCallback {
                                        override fun success() {
                                            super.success()
                                            toastCenter("提交成功")
                                            //刷新值机列表
                                            checkInListRefreshFlag.longValue =
                                                System.currentTimeMillis()
                                            dismiss()
                                            //保存值机岛选择
                                            AppDataStore.saveCheckInIsland(selectedIsland.value)
                                        }
                                    }
                                )
                            }

                        }
                    ) {
                        Text(
                            text = "提交",
                            fontSize = R.dimen.d14.dimenToSp(),
                            fontWeight = FontWeight.W400,
                            color = R.color.white.toComposeColor(),
                            modifier = Modifier.align(Alignment.Center)
                        )
                    }
                }
            }
        }
    }

    @Composable
    private fun ColumnScope.CheckInIslandView(
        onSelectedIsland: (String) -> Unit
    ) {
        val defaultIndex = 0
        val currentIndex = remember { mutableIntStateOf(defaultIndex) }
        val viewModel: CheckInViewModel = viewModel(context as AppCompatActivity)
        val checkInAreaList = viewModel.checkInAreaList.value ?: emptyList()

        val itemSpace = R.dimen.d6.dimenToDp()
        // 按区域分组
        val areaMap = checkInAreaList.groupBy { it.area }

        val checkIngIsland = areaMap.keys.map { TabRowItem(it) }

        var selectIsland: (Int) -> Unit = {}

        if (checkIngIsland.isNotEmpty()) {
            val checkInStation = areaMap[checkIngIsland[currentIndex.intValue].title] ?: emptyList()

            Row(
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = "值机柜台",
                    fontSize = R.dimen.d14.dimenToSp(),
                    fontWeight = FontWeight.W500,
                    color = R.color.black_33.toComposeColor(),
                )
                HorizontalSpace(R.dimen.d10.dimenToDp())
                SwitchTab(
                    tabRowItems = checkIngIsland,
                    onSelectIndex = {
                        if (currentIndex.intValue != it) {
                            //复原选中值机柜台
                            checkInStation.forEach {
                                it.checked.value = false
                            }
                            currentIndex.intValue = it
                            onSelectedIsland(checkIngIsland[it].title)
                        }
                    },
                    defaultIndex = defaultIndex,
                    bottomHeight = R.dimen.d20.dimenToDp(),
                    bottomBgColor = R.color.transparent.toComposeColor(),
                    bottomCornerRadius = 0.dp,
                    selectedTextColor = statusBarColor.toComposeColor(),
                    unSelectedTextColor = R.color.black_66.toComposeColor(),
                    selectedTextSize = R.dimen.d16.dimenToDp(),
                    unSelectedTextSize = R.dimen.d14.dimenToDp(),
                    padding = 0.dp,
                    isShowZero = false,
                    slideBarGapWidth = R.dimen.d1.dimenToDp(),
                    slideBarWidth = R.dimen.d30.dimenToDp(),
                    slideBarBgColor = R.color.transparent.toComposeColor(),
                    slideBarCornerRadius = R.dimen.d2.dimenToDp(),
                    onPerformClick = {
                        selectIsland = it
                    }
                )
            }


            //值机岛列表
            LazyVerticalGrid(
                columns = GridCells.Fixed(count = 7),
                modifier = Modifier.background(R.color.white.toComposeColor())
                    .padding(top = R.dimen.d16.dimenToDp())
                    .fillMaxWidth()
                    .heightIn(min = R.dimen.d30.dimenToDp(), max = R.dimen.d50.dimenToDp()),
                horizontalArrangement = Arrangement.spacedBy(itemSpace),
                verticalArrangement = Arrangement.spacedBy(itemSpace)
            ) {
                items(checkInStation, key = { it.id }) {
                    Box(
                        modifier = Modifier.fillMaxWidth().height(R.dimen.d22.dimenToDp())
                            .background(
                                color = if (it.checked.value)
                                    statusBarColor.toComposeColor()
                                else
                                    R.color.gray_ECEFF4.toComposeColor(),
                                shape = RoundedCornerShape(R.dimen.d2.dimenToDp())
                            ).intervalClick {
                                checkInStation.forEach {
                                    it.checked.value = false
                                }
                                it.checked.value = true
                                //赋值选择的值机柜台
                                areaBO.value = it
                            },
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = it.title,
                            fontSize = R.dimen.d14.dimenToSp(),
                            fontWeight = FontWeight.W400,
                            color = if (it.checked.value)
                                R.color.white.toComposeColor()
                            else
                                R.color.black_66.toComposeColor()
                        )
                    }
                }
            }
        }



        LaunchedEffect(Unit) {
            viewModel.getCheckInAreaList()
        }

        //取默认缓存的值机岛
        LaunchedEffect(areaMap) {
            if (areaMap.isNotEmpty()) {
                AppDataStore.getCheckInIsland().ifEmpty { null }?.let { cache ->
                    val index = areaMap.keys.indexOfFirst { it == cache }
                    if (index != -1) {
                        selectIsland.invoke(index)
                    }
                }
            }
        }
    }

    @Composable
    private fun ColumnScope.CheckInPersonView() {

        CheckInPersonItemView(
            title = "保障人员：",
            value = userBO.value?.username.dealString(),
            onSelected = {})
        VerticalSpace(R.dimen.d4.dimenToDp())
        CheckInPersonItemView(
            title = "计划开始：",
            value = startTime.longValue.formatTimeHMWithDay(),
            onSelected = {
                //设置回调
                setSelectTimeCallback(object : SelectTimeListener {
                    override fun onSelectTime(date: String, time: Long) {
                        startTime.longValue = time
                    }
                })
                showDatePicker(startTime.longValue.formatTimeYMDHM())
            })
        VerticalSpace(R.dimen.d4.dimenToDp())
        CheckInPersonItemView(
            title = "计划完成：",
            value = endTime.longValue.formatTimeHMWithDay(),
            onSelected = {
                //设置回调
                setSelectTimeCallback(object : SelectTimeListener {
                    override fun onSelectTime(date: String, time: Long) {
                        if (time > startTime.longValue) {
                            endTime.longValue = time
                        } else {
                            toastCenter("计划完成时间不能小于计划开始时间")
                        }
                    }
                })

                showDatePicker(endTime.longValue.formatTimeYMDHM())
            })

    }

    @Composable
    private fun CheckInPersonItemView(
        title: String,
        value: String,
        onSelected: () -> Unit
    ) {
        Row(
            modifier = Modifier.intervalClick {
                onSelected()
            },
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                text = title,
                fontSize = R.dimen.d14.dimenToSp(),
                fontWeight = FontWeight.W400,
                color = R.color.black_33.toComposeColor(),
            )

            Text(
                text = value,
                fontSize = R.dimen.d14.dimenToSp(),
                fontWeight = FontWeight.W400,
                color = statusBarColor.toComposeColor()
            )
        }
    }

    private fun validateData(): Boolean {
        //验证值机柜台数据
        assert(areaBO.value != null) {
            toastCenter("请选择值机柜台")
            return false
        }

        //验证计划开始时间
        assert(startTime.longValue <= endTime.longValue) {
            toastCenter("开始时间必须小于完成时间")
            return false
        }

        return true
    }

    fun setUser(user: CheckInPerSonBO) {
        userBO.value = user
    }

    override fun getPopupHeight(): Int {
        return (ScreenUtils.getScreenHeight() * 0.5).toInt()
    }
}